/*
 * 文件名：Dom4JUtil.java
 * 版权：Copyright by www.suyin.net
 * 描述：Dom4J工具类
 * 修改人：cqm
 * 修改时间：2011-12-9
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
package com.caiyouxi.pay.payment.weixin.wxpay;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * Dom4J工具类
 * @author cqm
 * @version 2011-12-9
 * @see Dom4JUtil
 * @since
 */
public class Dom4JUtil
{

    /**
     * 
     * Description: 将xml字符串转化为Document对象<br>
     * @param xml xml字符串
     * @return Document对象
     * @throws UnsupportedEncodingException
     * @throws DocumentException 
     * @see
     */
    public static Document stringToDocument(String xml)
        throws UnsupportedEncodingException, DocumentException
    {
        SAXReader reader = new SAXReader();
        ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
        Reader r = new InputStreamReader(is);
        Document document = reader.read(r);
        return document;
    }

    /**
     * 
     * Description:获得根节点名 <br>
     * @param document doc对象
     * @return 
     * @see
     */
    public static String getRootElementName(Document document)
    {
        String root = "";
        Element ele = document.getRootElement();
        if (ele != null)
        {
            root = ele.getName();
        }
        return root;
    }

    /**
     * 
     * Description: 获得XML节点对应的元素集合<br>

     * @param document Document对象（xml字符串可通过stringToDocument方法转换为其）
     * @param nodes 节点（遵循XPath形式 如：/recordList/record）
     * @return
     * @throws UnsupportedEncodingException
     * @throws DocumentException 
     * @see
     */
    @SuppressWarnings("unchecked")
    public static List<Element> getElements(Document document, String nodes)
        throws UnsupportedEncodingException, DocumentException
    {
        List<Element> list = document.selectNodes(nodes);
        return list;
    }

    /**
     * 
     * Description: 增加节点<br>
     * @param document doc对象
     * @param nodes 节点（遵循XPath形式 如：/recordList/record）
     * @param childElementName 增加的节点
     * @return 
     * @see
     */
    @SuppressWarnings("rawtypes")
    public static String addXMLElement(Document document, String nodes, String childElementName)
    {
        List list = document.selectNodes(nodes);
        Iterator iter = list.iterator();
        while (iter.hasNext())
        {
            Element parentElement = (Element)iter.next();
            parentElement.addElement(childElementName);
        }
        return document.asXML();
    }

    /**
     * 
     * Description:获得元素对应的节点的属性值 <br>
     * @param element 元素
     * @param node 节点（遵循XPath形式 如：/recordList/record）
     * @return 
     * @see
     */
    public static String getElementAttribute(Element element, String node)
    {
        String value = "";
        Node nd = element.selectSingleNode(node);
        if (nd != null)
        {
            value = nd.getStringValue();
        }
        return value;
    }

    /**
     * 
     * Description:获得元素对应的节点的属性值 <br>
     * @param document doc对象
     * @param node 节点（遵循XPath形式 如：/recordList/record）
     * @return 
     * @see
     */
    public static String getElementAttribute(Document document, String node)
    {
        String value = "";
        Node nd = document.selectSingleNode(node);
        if (nd != null)
        {
            value = nd.getStringValue();
        }
        return value;
    }

    /**
     * 
     * Description: 删除节点（如果该节点含有子节点 则子节点将一并被删除）<br>
     * @param document doc对象
     * @param nodes 节点（遵循XPath形式 如：/recordList/record）
     * @param childElementName 删除的节点
     * @return 
     * @see
     */
    @SuppressWarnings("rawtypes")
    public static String deleteXMLElement(Document document, String nodes, String childElementName)
    {
        List list = document.selectNodes(nodes);
        Iterator iter = list.iterator();
        while (iter.hasNext())
        {
            Element parentElement = (Element)iter.next();
            Iterator childIterator = parentElement.elementIterator(childElementName);

            while (childIterator.hasNext())
            {
                Element childElement = (Element)childIterator.next();
                parentElement.remove(childElement);
            }
        }
        return document.asXML();
    }

    /**
     * 
     * Description: 修改XML根节点名<br>
     * @param document doc对象
     * @param reRootEleName 
     * @return 
     * @see
     */
    public static String modifyXMLRootElementName(Document document, String reRootEleName)
    {
        Element ele = document.getRootElement();
        if (ele != null)
        {
            ele.setName(reRootEleName);
        }
        return document.asXML();
    }

    /**
     * 
     * Description: 修改节点属性<br>
     * @param document Document对象（xml字符串可通过stringToDocument方法转换为其）
     * @param nodes 节点 （遵循XPath形式 如：/recordList/record）
     * @param dValue 节点属性值
     * @return
     * @throws UnsupportedEncodingException
     * @throws DocumentException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    public static String modifyXMLElementValue(Document document, String nodes, String dValue)
        throws UnsupportedEncodingException, DocumentException
    {
        List list = getElements(document, nodes);
        Iterator iter = list.iterator();
        while (iter.hasNext())
        {
            Element element = (Element)iter.next();
            element.setText(dValue);
        }
        return document.asXML();
    }

    /**
     * 修改节点属性值
     * @param document 目前文件
     * @param map  需要修改的属性名称和值
     * @return
     * @throws UnsupportedEncodingException
     * @throws DocumentException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    public static String modifyXMLElementValue(Document document, Map<String, String> map)
        throws UnsupportedEncodingException, DocumentException
    {
        for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();)
        {
            String node = iterator.next();
            List list = document.selectNodes(node);
            Iterator iter = list.iterator();
            while (iter.hasNext())
            {
                Element element = (Element)iter.next();
                element.setText(map.get(node));
            }
        }
        return document.asXML();
    }

}
